package com.jingdianjichi.subject.application.interceptor;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Description: Feign请求拦截器：拦截Feign请求，并封装用户loginId到Feign请求包中
 *              原因：subject微服务调用auth微服务，需要Feign发送请求
 *                      但是Feign请求是独立请求，与前端请求不一致，不会携带用户基本信息
 * @return:
 * @Author:  sky
 * @date:  2024/11/24 21:45
 */
//@Component
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 从请求上下文中，拿到前端请求包
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        if(Objects.nonNull(request)){
            // 获取请求头里面的loginId
            String loginId = request.getHeader("loginId");
            if(StringUtils.isNotBlank(loginId)){
                // 封到Feign请求头里面
                requestTemplate.header("loginId",loginId);
            }
        }
    }
}
